package com.common.app.widget.sysno;

import android.content.Context;
import android.graphics.drawable.Animatable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.common.app.R;
import com.common.app.data.bean.SysListDataModel;
import com.common.app.widget.mybanner.transformer.OverlayTransformer;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.tencent.smtt.sdk.WebView;

import java.util.List;

public abstract class BaseSysOverlayPageAdapter extends PagerAdapter {
    private Context context;
    private List<SysListDataModel> imgUrls;
    private SysListDataModel curBean;

    public BaseSysOverlayPageAdapter(Context context) {
        this.context = context;
    }

    /**
     * item布局
     *
     * @return
     */
    protected abstract View itemView();

    public void setImgUrlsAndBindViewPager(ViewPager vp, List<SysListDataModel> imgUrls) {
        setImgUrlsAndBindViewPager(vp, imgUrls, 3);
    }

    public void setImgUrlsAndBindViewPager(ViewPager vp, List<SysListDataModel> imgUrls, int layerAmount) {
        setImgUrlsAndBindViewPager(vp, imgUrls, layerAmount, -1, -1);
    }

    /**
     * @param vp
     * @param imgUrls
     * @param layerAmount 显示层数
     */
    public void setImgUrlsAndBindViewPager(ViewPager vp, List<SysListDataModel> imgUrls, int layerAmount, float scaleOffset, float transOffset) {
        this.imgUrls = imgUrls;
        if (imgUrls != null && imgUrls.size() > 0) {
//            bitmaps = new WeakReference[imgUrls.size()];
            vp.setOffscreenPageLimit(layerAmount);
            OverlayTransformer transformer = new OverlayTransformer(layerAmount, scaleOffset, transOffset);
            vp.setPageTransformer(true, transformer);
        }

        if (this.imgUrls != null && !imgUrls.isEmpty()) {
            curBean = this.imgUrls.get(0);
        }
    }

    @Override
    public int getCount() {
//        //无限循环
//        if (null == imgUrls)
//            return 0;
//        if (imgUrls.size() <= 1)
//            return imgUrls.size();
//        return Integer.MAX_VALUE;

        //不循环
        return imgUrls.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    protected ConstraintLayout findBgView(View rootView) {
        ConstraintLayout bg = rootView.findViewById(R.id.body_bg_cv);
        if (null != bg)
            return bg;
        if (rootView instanceof ConstraintLayout) {
            return (ConstraintLayout) itemView();
        }
        throw new RuntimeException("you should set one of ImageViews id=card_iv or rootView=ImageView");
    }
    protected TextView findTitleView(View rootView) {

        TextView title = rootView.findViewById(R.id.item_title);
        if (null != title)
            return title;
        if (rootView instanceof TextView) {
            return (TextView) itemView();
        }
        throw new RuntimeException("you should set one of ImageViews id=card_iv or rootView=ImageView");
    }
    protected WebView findImageView2(View rootView) {
        WebView iv = rootView.findViewById(R.id.item_body_details_wv);
        if (null != iv)
            return iv;
        if (rootView instanceof WebView) {
            return (WebView) itemView();
        }
        throw new RuntimeException("you should set one of ImageViews id=card_iv or rootView=ImageView");
    }

    static class MyControllerListener implements ControllerListener<ImageInfo> {

        private SimpleDraweeView view;

        private boolean isMeasured;

        private int screenWidth;
        private int screenHeight;

        public MyControllerListener(SimpleDraweeView view, int screenWidth, int screenHeight) {
            this.view = view;
            this.screenWidth = screenWidth;
            this.screenHeight = screenHeight;
        }

        @Override
        public void onFailure(String arg0, Throwable arg1) {

        }

        @Override
        public void onFinalImageSet(String arg0, ImageInfo info, Animatable arg2) {
            measured(info);
        }

        @Override
        public void onIntermediateImageFailed(String arg0, Throwable arg1) {

        }

        @Override
        public void onIntermediateImageSet(String arg0, ImageInfo arg1) {

        }

        @Override
        public void onRelease(String arg0) {

        }

        @Override
        public void onSubmit(String arg0, Object arg1) {

        }

        private void measured(ImageInfo info) {
            if (isMeasured) {
                return;
            }
            isMeasured = true;

            // 获取图片真实宽高
            int width = info.getWidth();
            int height = info.getHeight();

            // 获取图片显示控件宽度,基于宽度适配图片
            int viewWidth = screenWidth;
            float viewRatio = viewWidth * 1.0f / width;
            view.setLayoutParams(new LinearLayout.LayoutParams(viewWidth, (int) (height * viewRatio)));
        }

    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        final int p = position % imgUrls.size();
        curBean = imgUrls.get(p);
        final String imgUrl = imgUrls.get(p).getContent();
        View view = itemView();
        if (null == view) {
            throw new RuntimeException("you should set a item layout");
        }
        ConstraintLayout bgView = findBgView(view);
        // 主题类型 1-发现、2-商城、3-念念、4-乐十
        switch (imgUrls.get(p).getThemeType()){
            case 2:
                bgView.setBackground(ContextCompat.getDrawable(this.context,R.drawable.bg_round_ef243a_10));
                break;
            case 3:
                bgView.setBackground(ContextCompat.getDrawable(this.context,R.drawable.bg_round_3ccbd2_10));
                break;
            case 4:
                bgView.setBackground(ContextCompat.getDrawable(this.context,R.drawable.bg_round_41b581_10));
                break;
            default:
                bgView.setBackground(ContextCompat.getDrawable(this.context,R.drawable.bg_round_product_10));
                break;
        }

        TextView title = findTitleView(view);
        title.setText(imgUrls.get(p).getTitle());

        final WebView iv = findImageView2(view);
        if (null == iv) {
            throw new RuntimeException("you should set a item layout");
        }

        String mData = imgUrl.replace("<br>", "");//去除换行符
//            binding?.bodyDetailsWv?.loadData(getNewWebData(mData), "text/html", "utf-8")
        iv.loadData(getNewWebData(mData), "text/html; charset=UTF-8", null);

        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }

    public SysListDataModel getCurBean() {
        return curBean;
    }

    public String getNewWebData(String htmltext) {
//        Document doc = Jsoup.parse(htmltext);
//        Elements elements = doc.getElementsByTag("img");
//        for (Element element : elements) {
//            element.attr("width", "100%")
//                    .attr("height", "auto");
//        }
//        return doc.toString();// 图片资源出问题时会无限拉长

        String newContent = "";
        if (!TextUtils.isEmpty(htmltext)) {
            newContent = htmltext.replace("<img", "<img style=\"display:        ;max-width:100%;\"");
        }

        return newContent;
    }

}
